import { t } from '@src/locales'
import draggable from 'vuedraggable'

import './BizSelectColumnSort.scss'

import { isEmpty } from '@src/util/type'
import { uuid } from 'pub-bbx-utils'

const NestedDraggable = {
  name: 'nested-draggable',
  props: {
    deleteSelect: Function,
    lists: {
      required: true,
      type: Array,
      default: () => []
    },
    noFix:{
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      drag: false,
      lastIndex:0
    }
  },
  computed: {
    fixedCols() {
      return this.lists.filter(item => {
        return item.fixLeft;
      });
    },
    fixedIndex() {
      return this.lists.findIndex(item => {
        return item.fixLeft === true
      });
    }
  },
  methods: {
    clearEmptyList(index) {
      this.lists.splice(index, 1)
      this.emitClearEventHandler()
    },
    deleteSortField(field, index) {
      field.fixLeft = false;
      if(!field.isSystem){
        this.lists.splice(index, 1)
      }
      this.emitDeleteEventHandler(field)
      this.emitClearEventHandler()
    },
    emitClearEventHandler() {
      if (isEmpty(this.lists)) {
        this.$emit('clear')
      }
    },
    emitDeleteEventHandler(field) {
      this.$emit('delete', field)
    },
    onDeletedSortFieldItemHandler(field) {
      this.emitDeleteEventHandler(field)
    },
    sortListDragStartEventHandler(event) {
      this.drag = true
    },
    sortListDragEndEventHandler(event) {
      this.drag = false
    },
    sortListMoveEventHandler(event) {
      // draggedContext 拖拽项；relatedContext 拖拽的目标；
      const { draggedContext, relatedContext } = event
      // show === 'important' 不允许拖拽 亦不允许以其为目标拖拽；
      if(relatedContext.element.show === 'important') return false
    },
    // 固定列首
    fixSortField(element, index) {
      element.fixLeft = !element.fixLeft
      this.lists.forEach((item, elIndex)=>{
        if(index != elIndex){
          item.fixLeft = false
        }
      })
      if (element.fixLeft) {
        this.moveEl(this.lists, index, 0);
        if(index != 0){
          this.moveEl(this.lists, 1, this.lastIndex);
        }
        this.lastIndex = index;
      } else {
        this.moveEl(this.lists, 0, this.lastIndex);
      }

    },
    // 移动元素(index是当前元素下标，tindex是拖动到的位置下标。)
    moveEl(arr, a, b) {
      arr.splice(b, 0, arr.splice(a, 1)[0]);
      return arr;
    }
  },
  render(h) {
    // 过滤掉子列表不存在数据的  和操作列
    const sortList = this.lists.filter(field => field.lists ? field.lists.length > 0 : true)
    
    return (
      <div style="width:100%">
        {this.fixedCols.map((field, index) => {
          return (
            <div class="nested-draggable-block nested-draggable-child undraggable">
              <div class="nested-draggable-name">
                <span class="nested-draggable-name-label">
                  {/* <i class="iconfont icon-tuozhuaipaixu"></i> */}
                </span>
                <span class="nested-draggable-name-text">
                  {index + 1}-{field.name || field.displayName}
                </span>
                <div class="nested-draggable-name-label-actions">
                  <span
                    class="nested-draggable-name-label nested-draggable-name-fixed"
                    onClick={() => this.fixSortField(field, index)}
                  >
                    <i
                      class="iconfont icon-pushpin-fill"
                      style={{color: this.getThemeColor}}
                    ></i>
                  </span>
                  <span
                    class="nested-draggable-name-label nested-draggable-name-delete"
                    onClick={() => this.deleteSortField(field, index)}
                  >
                    <i class="iconfont icon-close-circle"></i>
                  </span>
                </div>
              </div>
            </div>
          );
        })}
        <draggable 
        // 单位：ms，定义排序动画的时间
          animation="180"
          class="nested-draggable"
          tag="div" 
          list={ this.lists }
          onStart={ (event) => this.sortListDragStartEventHandler(event) }
          onEnd={ (event) => this.sortListDragEndEventHandler(event) }
          // 忽略 HTML5拖拽行为，强制回调进行
          forceFallback
          // 当使用forceFallback的时候，被复制的dom的css类名
          fallbackClass="sortable-fallback"
          // 将cloned DOM 元素挂到body元素上。
          fallbackOnBody
          // 不允许拖拽 field.show === 'important'
          filter=".undraggable"
          move={ (event) => this.sortListMoveEventHandler(event) }
        >
          {
            sortList.map((field, index) => {
              return (
                <div>
                  {!field.fixLeft ? (
                    <div key={uuid()} class={`nested-draggable-block nested-draggable-child ${field.show === 'important' ? 'undraggable' : 'draggable'}`}>
                      <div class="nested-draggable-name">
                        <span class="nested-draggable-name-label"><i class="iconfont icon-tuozhuaipaixu"></i></span>
                        <span class={`nested-draggable-name-text ${this.noFix ? 'nested-draggable-name-text-noFix' : ''}`}>{ index < this.fixedIndex ? index + 2 : index + 1}-{ field.name || field.displayName }</span>
                        {
                          (!field.lists && field.show !== 'important') && (
                            <div class="nested-draggable-name-label-actions">
                              {!this.noFix && (<span
                                class="nested-draggable-name-label nested-draggable-name-fixed"
                                onClick={() => this.fixSortField(field, index)}
                              >
                                <el-tooltip
                                  class="item"
                                  effect="dark"
                                  content={t('component.bizSelectCol.fixedTip')}
                                  placement="top"
                                >
                                  <i class="iconfont icon-pushpin"></i>
                                </el-tooltip>
                              </span>)}
                              {this.noFix && (<span
                                class="nested-draggable-name-label nested-draggable-name-fixed"
                              >
                              </span>)}
                              <span
                                class="nested-draggable-name-label nested-draggable-name-delete"
                                onClick={() => this.deleteSortField(field, index)}
                              >
                                <i class="iconfont icon-close-circle"></i>
                              </span>
                            </div>
                          )
                        }
                      </div>
                      <nested-draggable
                        lists={field.lists}
                        noFix={true}
                        onDelete={field => this.onDeletedSortFieldItemHandler(field)}
                        onClear={() => this.clearEmptyList(index)}
                      >
                      </nested-draggable>
                    </div>)
                    : (
                      ''
                    )}
                </div>
              );
            })
          }
        </draggable>
      </div>
    )
  },
  components: {
    draggable
  },
}

const BizSelectColumnSort = {
  name: 'biz-select-column-sort',
  props: {
    deleteSelect: Function,
    lists: {
      required: true,
      type: Array,
      default: () => [],
    }
  },
  methods: {
    onDeletedSortFieldItemHandler(field) {
      this.$emit('delete', field)
    }
  },
  render(h) {
    return (
      <div class="biz-select-column-sort">
        { this.$slots.title }
        <nested-draggable
          class='nested-draggable-root'
          lists={ this.lists }
          deleteSelect={(item, index) => this.deleteSelect(item, index)}
          onDelete={(item) => this.onDeletedSortFieldItemHandler(item)}
        >
        </nested-draggable>
      </div>
    )
  },
  components: {
    draggable,
    [NestedDraggable.name]: NestedDraggable
  }
}

export default BizSelectColumnSort;